package com.eco.fanliapp.job.delayjob;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eco.fanliapp.common.constant.NewsEnumLog;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.entity.*;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.utils.BigDecimalUtils;
import com.eco.fanliapp.utils.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 大额延迟定时扫描
 */
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
public class DelayTask implements Job, Serializable {


    private static final Logger log = LoggerFactory.getLogger(DelayTask.class);

    @Autowired
    private IAppUserOrderService iAppUserOrderService;
    @Autowired
    private IAppUserService iAppUserService;
    @Autowired
    private IAppNewsLogService iAppNewsLogService;
    @Autowired
    private IAppOrderDetailService iAppOrderDetailService;
    @Autowired
    private IGoodsFreeService iGoodsFreeService;
    @Autowired
    private ISySwitchService iSySwitchService;
    @Autowired
    private ISyUserMoneyLogService syUserMoneyLogService;
    @Autowired
    private IAppWxWithdrawalService iAppWxWithdrawalService;

    public DelayTask() {
    }

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        //取得job详情
        JobDetail jobDetail = context.getJobDetail();

        JobDataMap dataMap =  jobDetail.getJobDataMap();

        int executeCount = 0;
        if (dataMap.containsKey("runCount")) {
            executeCount = dataMap.getInt("runCount");
        }

        // 增量计数并将其存储回 JobDataMap，这样可以适当保持工作状态
        executeCount++;
        dataMap.put("runCount", executeCount);

        long startTime = System.currentTimeMillis();
        log.info("***************************************开始执行大额延迟定时扫描任务-DelayTask：executeCount=" + executeCount + "--startTime=" + startTime);
        Long stime = DateFormatUtils.getStartTime();
        Long etime = DateFormatUtils.getEndTime();
        try {
            List<AppUserOrder> userOrders = iAppUserOrderService.selectLargeAmountYesList(stime,etime);
            for (AppUserOrder appUserOrder : userOrders) {
                AppUser user = iAppUserService.selectAppUserByUserId(appUserOrder.getUserId());
                AppOrderDetail appOrderDetail = iAppOrderDetailService.selectAppOrderDetailByTradeId(appUserOrder.getOrderId());
                if(user != null && user.getEnable() != 0) {//0=禁用

                    AppUserOrder appUserOrder_new = new AppUserOrder();
                    appUserOrder_new.setTableId(appUserOrder.getTableId());
                    appUserOrder_new.setOrderSettleStatus(2);

                    int i =iAppUserOrderService.updateAppUserOrder(appUserOrder_new);
                    BigDecimal beforeBalance=user.getBalance();
                    if (i > 0) {
                        //查询是否是免单库的商品
                        GoodsFree goods = iGoodsFreeService.selectByGoodsId(appOrderDetail.getItemId());
                        if (goods != null && appOrderDetail.getGoodFrees() != null && appOrderDetail.getGoodFrees() == 1) {
                            int i6 = iAppUserService.updateAppUseraddbalance(user.getUserId(),
                                    BigDecimalUtils.Format(appUserOrder.getCommission()));
                            log.info("message{}免单{}", user.getUserId(), appUserOrder.getCommission());
                            log.info("免单商品大额延迟开始发送消息{}",i6);
                            if (i6 > 0 && isSendMsg(8)) {
                                //新增用户余额变动日志记录
                                syUserMoneyLogService.addSyUserMoneyLog(user.getUserId(),beforeBalance,BigDecimalUtils.Format(appUserOrder.getCommission()),"免单商品分佣",2,0);
                                iAppNewsLogService.newsType(user.getUserId(),
                                        NewsEnumLog.NEWS_FREE_BIGDELAY.getNewsType(),
                                        BigDecimalUtils.Format(appUserOrder.getCommission()), goods.getGoodsName(), appUserOrder.getCommission().toString());
                            }

                            try {
                                //公众号发送消息
                                // TODO: 结算成功公众号提醒
                                ServerResponse<String> result = iAppWxWithdrawalService.sendCashMessage(user,"30006",appOrderDetail.getTradeId().toString(), appUserOrder.getCommission().toString(),appOrderDetail.getTkEarningTime(),user.getWechatNickname());
                                log.info("公众号发消2息返回结果{}", JSONObject.toJSONString(result));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            //计算总佣金
                            // iGoodsFreeService.updateTotalRetureAmountByGoodsId(goods.getId());
                        }else {
                            switch (appUserOrder.getOrderGrade()) {
                                case 1:
                                    int i3 = iAppUserService.updateAppUseraddbalance(appUserOrder.getUserId(),
                                            BigDecimalUtils.Format(appUserOrder.getCommission()));
                                    log.info("message{}自己{}", appUserOrder.getUserId(), appUserOrder.getCommission());
                                    log.info("普通商品大额延迟开始发送消息{}",i3);
                                    if (i3 > 0 && isSendMsg(8)) {
                                        //新增用户余额变动日志记录
                                        syUserMoneyLogService.addSyUserMoneyLog(user.getUserId(),beforeBalance,BigDecimalUtils.Format(appUserOrder.getCommission()),"普通商品大额延迟给自己分佣",2,0);
                                        iAppNewsLogService.newsType(appUserOrder.getUserId(),
                                                NewsEnumLog.NEWS_AWARD_BIGDELAY.getNewsType(),
                                                BigDecimalUtils.Format(appUserOrder.getCommission()),"淘宝网", appOrderDetail.getItemTitle(), appUserOrder.getCommission().toString());
                                    }

                                    try {
                                        //公众号发送消息
                                        // TODO: 结算成功公众号提醒
                                        String time = DateFormatUtils.dateToString(new Date());
                                        ServerResponse<String> result = iAppWxWithdrawalService.sendCashMessage(user,"30006",appOrderDetail.getTradeId().toString(), appUserOrder.getCommission().toString(),time,user.getWechatNickname());
                                        log.info("公众号发消2息返回结果{}", JSONObject.toJSONString(result));
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }

                                    break;
                                /*case 2:
                                    int i4 = iAppUserService.updateAppUseraddbalance(appUserOrder.getUserId(),
                                            BigDecimalUtils.Format(appUserOrder.getCommission()));
                                    log.info("message{}2级{}", appUserOrder.getUserId(), appUserOrder.getCommission());
                                    log.info("普通商品大额延迟开始发送消息{}",i4);
                                    if (i4 > 0 && isSendMsg(8)) {
                                        //新增用户余额变动日志记录
                                        syUserMoneyLogService.addSyUserMoneyLog(user.getUserId(),beforeBalance,BigDecimalUtils.Format(appUserOrder.getCommission()),"普通商品大额延迟上级分佣",2,0);
                                        iAppNewsLogService.newsType(appUserOrder.getUserId(),
                                                NewsEnumLog.NEWS_ORDER_SUPER_SETTLE.getNewsType(),
                                                BigDecimalUtils.Format(appUserOrder.getCommission()),  appUserOrder.getCommission().toString());
//                                        iAppNewsLogService.newsType(appUserOrder.getUserId(),
//                                                NewsEnumLog.NEWS_AWARD_BIGDELAY.getNewsType(),
//                                                BigDecimalUtils.Format(appUserOrder.getCommission()), appOrderDetail.getItemTitle(),appUserOrder.getCommission().toString());
                                    }
                                    break;*/
                                default:
                                    break;
                            }
                        }
                    }

                    log.info("扫描到{}订单，金额为{}，用户为{}，结算状态{}，结果{}",
                            appUserOrder.getOrderId(),
                            appUserOrder.getCommission(),
                            appUserOrder.getUserId(),
                            appUserOrder.getOrderSettleStatus(),
                            i);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("执行大额延迟定时扫描任务错误");
        }
        long endTime = System.currentTimeMillis();
        log.info("***************************************结束执行大额延迟定时扫描任务-DelayTask：executeCount=" + executeCount + "--endTime=" + endTime + "--耗时=" + (endTime - startTime));
    }


    /**
     * 判断是不是今天
     * @param s
     * @param s2
     * @return
     */
    private Boolean isToDay(Long s , Long s2) {

        return DateUtils.isSameDay(new Date(s), new Date(s2));
    }

    /**
     * 通过开关判断是否要发消息
     * @id 开关类型
     * @return
     */
    private Boolean isSendMsg(int id) {
        //查询开关表是否发消息
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("table_id", id);
        SySwitch sySwitch = iSySwitchService.getOne(queryWrapper);
        if (sySwitch == null) return false;
        if (sySwitch.getState() == 1) {
            log.info("消息类型{} 消息开发送消息",id);
            return true;
        }
        log.info("消息类型{} 消息关",id);
        return false;
    }
}
